//
//  YiDongSubscription.m
//  QiYReader
//
//  Created by 奇阅科技 on 15/3/5.
//  Copyright (c) 2015年 奇阅科技. All rights reserved.
//

#import "YiDongSubscription.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "ZMYLKDB.h"
#import "ZMYNetWorkAPI.h"
#import <MessageUI/MFMessageComposeViewController.h>
@interface YiDongSubscription ()
{
    NSString *loginUrl;
    NSDictionary *subDict;
    BOOL isForgetView;
    NSString *phoneNum;
}
@property (weak,nonatomic)MBProgressHUD *progressHud;
@end
@implementation YiDongSubscription
-(void)awakeFromNib{
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self layoutSubviews];
    self.centreView.layer.cornerRadius = 10;
    self.centreView.hidden = YES;
    self.subscriptionView.layer.cornerRadius = 10;
    self.subscriptionView.hidden = YES;
    self.regsterView.layer.cornerRadius = 10;
    self.regsterView.hidden = YES;
    self.subWebActivity.hidden = YES;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
}
//-(NSString*)getCellularProviderName{
//    //获取运营商
//    CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc]init];
//    CTCarrier *carrier = [netInfo subscriberCellularProvider];
//    NSLog(@"carrier:%@",carrier);
//    return carrier.carrierName;;
//}
-(MBProgressHUD *)progressHud{
    if (!_progressHud) {
        _progressHud = [MBProgressHUD showHUDAddedTo:[AppDelegate delegate].window animated:YES];
        self.progressHud.removeFromSuperViewOnHide = YES;
        self.progressHud.dimBackground = YES;
        self.progressHud.mode = MBProgressHUDModeDeterminate;
        self.progressHud.detailsLabelText = @"加载中...";
        self.progressHud.removeFromSuperViewOnHide=YES;
    }
    return _progressHud;
}
-(void)beginVerificationReadPermissionsSucceed:(void(^)(void))succeedRefresh Fail:(void(^)(void))failRefresh Cancel:(void(^)(void))cancelRefresh{
    [AppDelegate hideAllHUD:[AppDelegate delegate].window];
    if (self.chapterId.length<6) {
        [self closeView:nil];
        failRefresh();
        return;
    }
    self.succeedSubscription = succeedRefresh;
    self.failSubscription = failRefresh;
    self.cancelSubscription = cancelRefresh;
    
    [self.progressHud show:YES];
    [self.progressHud setProgress:0.1];
    
    //判断本地有没有章节内容，有就可以进行阅读，没有进行订阅扣费
    [self bookChapterTextVerification];
}
#pragma mark 判断本地是否有章节内容
-(void)bookChapterTextVerification{
        if ([[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:self.chapterId]) {
            //判断本地是否有该章节内容
            [self.progressHud setProgress:1];
            [self.progressHud hide:YES];
            [self closeView:nil];
            self.succeedSubscription();
        }else{
            [self.progressHud setProgress:0.1];
            //如果本地没有该章节内容
            [self downloadChapterText];
        }
}
-(void)downloadChapterText{
    [[ZMYNetWorkAPI default]getYiDongChapterText:self.book ChapterID:self.chapterId ResultBlock:^(NSDictionary *resultDic) {
        if ([resultDic objectForKey:@"BookChapterText"]!=nil) {
            //下载成功
            [self closeView:nil];
            self.succeedSubscription();
        } else if ([resultDic objectForKey:@"loginSubmitUrl"]!=nil) {
            //需要重新登录
            loginUrl = [resultDic objectForKey:@"loginSubmitUrl"];
            [self showLoginView];
        } else if ([resultDic objectForKey:@"subscriptionView"]!=nil) {
            //订阅信息
            subDict = [resultDic objectForKey:@"subscriptionView"];
            if ([subDict objectForKey:@"orderUrl"]!=nil) {
                UserAccount *user = [UserAccount currentAccount];
                if (user.auto_subscription||!user) {
                    //如果是自动订阅，就去申请扣费
                    [self.progressHud setProgress:0.4];
                    [self chargeForYiDongLogin:[[subDict objectForKey:@"orderUrl"] substringFromIndex:1]];
                } else {
                    [self showSubscriptionView];
                }
            } else {
                [self showSubscriptionView];
            }
        }
    } error:^(NSString *errorStr) {
        NSLog(@"%@",errorStr);
        [AppDelegate showHUDAndHide:@"章节下载失败" view:[AppDelegate delegate].window];
        [self closeView:nil];
        self.failSubscription();
    }];
}
-(void)chargeForYiDongLogin:(NSString *)url{
    [self.progressHud setProgress:0.5];
    [self.progressHud show:YES];
    [[ZMYNetWorkAPI default]chargeForYiDongLogin:url ResultBlock:^(NSDictionary *resultDic) {
        NSString *chapterTextString = [resultDic objectForKey:@"content"];
        [self.progressHud setProgress:0.6];
        if (chapterTextString.length>50) {
            BookChapterText *chapterText = [BookChapterText new];
            chapterText.articleid = self.book.articleid;
            chapterText.chapterName = [resultDic objectForKey:@"name"];
            chapterText.chapterTextString = chapterTextString;
            chapterText.chapterId = self.chapterId;
            [[ZMYLKDB getLKDBHelper] updateBookChapterText:chapterText];
            [self closeView:nil];
            self.succeedSubscription();
        }else{
            [AppDelegate showHUDAndHide:@"章节付费失败" view:[AppDelegate delegate].window];
            [self closeView:nil];
            self.failSubscription();
        }
    } error:^(NSString *errorStr) {
        [self.progressHud hide:YES];
        [AppDelegate showHUDAndHide:@"章节付费失败" view:[AppDelegate delegate].window];
        [self closeView:nil];
        self.failSubscription();
    }];
}
-(void)showLoginView{
    //显示登录页面
    [self.progressHud hide:YES];
    self.centreView.hidden = NO;
    self.regsterView.hidden = YES;
    self.subscriptionView.hidden = YES;
}
-(void)showSubscriptionView{
    //显示订阅页面
    [self.progressHud hide:YES];
    self.centreView.hidden = YES;
    self.regsterView.hidden = YES;
    self.subscriptionView.hidden = NO;
    self.subWebView.hidden = YES;
    [self.subWebView setScalesPageToFit:NO];
    NSString *note1 = [subDict objectForKey:@"buyMsg"]?[subDict objectForKey:@"buyMsg"]:[subDict objectForKey:@"orderMsg"];
    self.subNotesLabel.text = note1?[NSString stringWithFormat:@"1、%@\n2、订阅和阅读书籍不能使用被窝阅币；\n3、和阅读书籍章节收费标准与被窝阅读收费不同；\n4、批量订阅可享受折扣优惠。",note1]:@"1、订阅和阅读书籍不能使用被窝阅币；\n2、和阅读书籍章节收费标准与被窝阅读收费不同；\n3、批量订阅可享受折扣优惠。";
}
-(void)showRechargeView{
    //显示订阅页面
    [self.progressHud hide:YES];
    self.centreView.hidden = YES;
    self.regsterView.hidden = YES;
    self.subscriptionView.hidden = NO;
    self.subWebView.hidden = NO;
    NSString *note1 = [subDict objectForKey:@"buyMsg"]?[subDict objectForKey:@"buyMsg"]:[subDict objectForKey:@"orderMsg"];
    self.subNotesLabel.text = note1?[NSString stringWithFormat:@"1、%@\n2、订阅和阅读书籍不能使用被窝阅币；\n3、和阅读书籍章节收费标准与被窝阅读收费不同；\n4、批量订阅可享受折扣优惠。",note1]:@"1、订阅和阅读书籍不能使用被窝阅币；\n2、和阅读书籍章节收费标准与被窝阅读收费不同；\n3、批量订阅可享受折扣优惠。";
}
-(void)hidenAllView{
    //隐藏所有的View，以防在调用closeView时调用self.cancelSubscription();
    [self.progressHud hide:YES];
    self.centreView.hidden = YES;
    self.regsterView.hidden = YES;
    self.subscriptionView.hidden = YES;
    self.subWebView.hidden = YES;
}
-(void)showRegsiterView{
    //显示注册页面
    [self.progressHud hide:YES];
    self.centreView.hidden = YES;
    self.regsterView.hidden = NO;
    self.subscriptionView.hidden = YES;
    if (isForgetView) {
        self.regsterTitleLabel.text = @"忘记密码";
        self.regsterNeedKnowLabel.text = @"重置密码须知:";
        self.regsterNoteLabel.text = @"1、根据您的运营商选择下列重置密码方式，发送您的新密码到指定号码即可；\n2、本次信息免费。";
        
    } else {
        self.regsterTitleLabel.text = @"注册";
        self.regsterNeedKnowLabel.text = @"注册须知:";
        self.regsterNoteLabel.text = @"1、和阅读注册只接受手机号码注册；\n2、和阅读注册根据相关规定，需发送一条免费密码短信以便第三方内容提供商验证用户真实性后完成注册。\n3、根据您的运营商选择下列注册方式，注册成功后会收到确认短信，然后进行登录，用户名就是您的手机号。\n4、忘记密码可以通过手机号找回密码。";
    }
}
- (IBAction)closeView:(id)sender {
    [self.progressHud hide:YES];
    if (self.subscriptionView.hidden == NO) {
        if (self.subWebView.hidden == NO) {
            [self showSubscriptionView];
        } else {
            [self removeFromSuperview];
            self.cancelSubscription();
        }
    } else if (self.regsterView.hidden == NO) {
        [self showLoginView];
    }else if (self.centreView.hidden == NO){
        [self removeFromSuperview];
        self.cancelSubscription();
    }else{
        //如果所有页面都处于隐藏状态则移除本封装
        [self removeFromSuperview];
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.textField1 resignFirstResponder];
    [self.textField2 resignFirstResponder];
}
- (IBAction)sureButtonClick:(id)sender {
    [self.textField1 resignFirstResponder];
    [self.textField2 resignFirstResponder];
        if ([self validateMobile:self.textField1.text]) {
            [self.progressHud show:YES];
            [self.progressHud setProgress:0.2];
            [[ZMYNetWorkAPI default] getYiDongLogin:@{@"uname":self.textField1.text,@"passwd":self.textField2.text,@"rememberUname":@"on"} ResultBlock:^(NSDictionary *resultDic) {
                if ([resultDic objectForKey:@"errorMsg"]!=nil) {
                    [self.progressHud hide:YES];
                    [AppDelegate showHUDAndHide:[resultDic objectForKey:@"errorMsg"] view:[AppDelegate delegate].window];
                } else if ([resultDic objectForKey:@"showName"]!=nil) {
                    subDict = resultDic;
                    if ([subDict objectForKey:@"orderUrl"]!=nil) {
                        //订阅信息
                        UserAccount *user = [UserAccount currentAccount];
                        if (user.auto_subscription||!user) {
                            //如果是自动订阅，就去申请扣费
                            [self.progressHud setProgress:0.4];
                            [self hidenAllView];
                            [self chargeForYiDongLogin:[[subDict objectForKey:@"orderUrl"] substringFromIndex:1]];
                        } else {
                            
                            [self showSubscriptionView];
                        }
                    } else {
                        [self showSubscriptionView];
                    }
                    
                }
            } error:^(NSString *errorStr) {
                [self.progressHud hide:YES];
                [AppDelegate showHUDAndHide:errorStr view:[AppDelegate delegate].window];
            }];
        }else{
            [AppDelegate showHUDAndHide:@"输入的手机号不正确，请重试" view:[AppDelegate delegate].window];
        }
}
//手机号码验证
-(BOOL)validateMobile:(NSString *)mobile
{
    //手机号以1开头，10个 \d 数字字符
    NSString *phoneRegex = @"^1\\d{10}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
- (IBAction)regsterClick:(id)sender {
    isForgetView = NO;
    [self showRegsiterView];
}
- (IBAction)forgetYiDongPWClick:(id)sender {
    isForgetView = YES;
    [self showRegsiterView];
}
- (IBAction)liantongClick:(id)sender {
    phoneNum = @"106554814018";
    [self sendMessage];
}
- (IBAction)yidongClick:(id)sender {
    phoneNum = @"106580808";
    [self sendMessage];
}
- (IBAction)dianxinClick:(id)sender {
    phoneNum = @"118170288";
    [self sendMessage];
}
-(void)sendMessage{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"免费"
                                                    message:@"稍后请在短信内容中输入你要设定的密码，然后点击发送，您会收到确认短信，本次短信免费"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"sms://%@",phoneNum]]];
        if (self.regsterView.hidden == NO) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                            message:@"待收到短信确认信息后即可进行登录"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            [self showLoginView];
        }
    }
}
#pragma mark - 订阅View点击事件
- (IBAction)subscription1Chapter:(id)sender {
    [self.progressHud hide:YES];
    if ([subDict objectForKey:@"orderUrl"]!=nil) {
        [self.progressHud setProgress:0.4];
        [self hidenAllView];
        [self chargeForYiDongLogin:[[subDict objectForKey:@"orderUrl"] substringFromIndex:1]];
    } else {
        [self showRechargeView];
        NSMutableURLRequest *reque = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://wap.cmread.com/r/p/pay_sjcz.jsp?vt=3&ln=9762_120982__2_&dataSrcId=26886831&sqId=L4"]];
        reque.timeoutInterval = 10;
        [self.subWebView loadRequest:reque];
    }
}
- (IBAction)subscription10Chapter:(id)sender {
    [self.progressHud hide:YES];
    if ([subDict objectForKey:@"buyTenUrl"]!=nil) {
        [self.progressHud setProgress:0.4];
        [self hidenAllView];
        [self chargeForYiDongLogin:[[subDict objectForKey:@"buyTenUrl"] substringFromIndex:1]];
    } else {
        [AppDelegate showHUDAndHide:@"本章节不能进行“20章”订阅，请尝试其他方式" view:[AppDelegate delegate].window];
    }
}
- (IBAction)subscription20Chapter:(id)sender {
    [self.progressHud hide:YES];
    if ([subDict objectForKey:@"buyTwentyUrl"]!=nil) {
        [self.progressHud setProgress:0.4];
        [self hidenAllView];
        [self chargeForYiDongLogin:[[subDict objectForKey:@"buyTwentyUrl"] substringFromIndex:1]];
    } else {
        [AppDelegate showHUDAndHide:@"本章节不能进行“20章”订阅，请尝试其他方式" view:[AppDelegate delegate].window];
    }
}
- (IBAction)subscriptionAnyChapter:(id)sender {
    [self.progressHud hide:YES];
    [AppDelegate showHUDAndHide:@"本书不提供分册订阅" view:[AppDelegate delegate].window];
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    self.subWebActivity.hidden = NO;
    [self.subWebActivity startAnimating];
    NSURL *url = [request URL];
    if ([[url scheme]isEqualToString:@"sms"]) {
//        [AppDelegate showHUDAndHide:@"暂不支持电信充值，请尝试其他方式" view:[AppDelegate delegate].window];
//        [webView goBack];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[[url query] substringFromIndex:5]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        phoneNum = [url host];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"内容已复制到剪切板"
                                                        message:@"稍后请在短信内容中粘贴剪切板中的文本，然后点击发送即可"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        self.subWebActivity.hidden = YES;
        return NO;
    }
    return YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [AppDelegate showHUDAndHide:@"网络请求失败，请稍后再试" view:[AppDelegate delegate].window];
    [self showSubscriptionView];
    self.subWebActivity.hidden = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *bodyWidth= [webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollWidth "];
    CGFloat initialScale = webView.frame.size.width/[bodyWidth intValue];
    //修改服务器页面的meta的值
    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=%.1f, minimum-scale=0.1, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width,initialScale-0.1];
    [webView stringByEvaluatingJavaScriptFromString:meta];
    self.subWebActivity.hidden = YES;
}


@end
